package com.jml.jdbc.annotationdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private JdbcTemplate jdbcTemplate ;

	@Autowired
	private UserService userService;

	@Transactional
	@Override
	public void save(User user) {
		jdbcTemplate.update("insert into user (name,age,sex) values (?,?,?)",
				new Object[]{user.getName(),user.getAge(),user.getSex()},
				new int[]{Types.VARCHAR,Types.INTEGER,Types.VARCHAR});
		//异常回滚
		/*int i = 0;
		int j = 10/i;*/
		userService.save001(user);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	@Override
	public void save001(User user) {
		jdbcTemplate.update("insert into user (name,age,sex) values (?,?,?)",
				new Object[]{"REQUIRES_NEW",user.getAge(),user.getSex()},
				new int[]{Types.VARCHAR,Types.INTEGER,Types.VARCHAR});
	}

	@Override
	public List<User> getUser() {
		return jdbcTemplate.query("select * from user",new UserRowMapper());
	}
}
